package com.sky.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersAggrDTOMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.result.Result;
import com.sky.service.*;
import com.sky.utils.UserThreadUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.namesrv.NamesrvUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author xieminghui
 * @since 2023-11-16
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Resource
    private IOrderDetailService orderDetailService;
    @Resource
    private OrderDetailMapper orderDetailServiceMappe;
    @Resource
    private OrdersAggrDTOMapper ordersAggrDTOMapper; //聚合类mapper
    @Resource
    private IAddressBookService iAddressBookService; //地址服务层
    @Resource
    private IUserService userService; // 用户服务处
    @Resource
    private IShoppingCarService iShoppingCarService; //购物车服务层
   // @Resource
   // private OrdersServiceImpl ordersService; // 注入本类对象,生成代理调用方法事务生效
  // @Resource
  // private WeChatPayUtil weChatPayUtil;
    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 统计所有状态订单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:31:48
     * @param: []
     * @return: com.sky.result.Result<com.sky.vo.OrderStatisticsVO>
     **/
    @Override
    public Result<OrderStatisticsVO> statisticsOrders() {
        QueryWrapper<OrdersAggrDTO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(OrdersAggrDTO::getStatus, OrdersAggrDTO::getCount)
                .groupBy(OrdersAggrDTO::getStatus);
        List<OrdersAggrDTO> list = ordersAggrDTOMapper.selectList(wrapper);
        // 分组结果封装到Map集合,因为可以多字段分组,所以返回的封装多个map集合的List集合
        if (list.size() == 0) {
            throw new BaseException("没有此类订单");
        }
        Map<Integer, Integer> collect = list.stream()
                .collect(Collectors.toMap(OrdersAggrDTO::getStatus, OrdersAggrDTO::getCount));
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 封装数据
        orderStatisticsVO.setConfirmed(collect.get(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(collect.get(Orders.DELIVERY_IN_PROGRESS));
        orderStatisticsVO.setToBeConfirmed(collect.get(Orders.TO_BE_CONFIRMED));
        return Result.success(orderStatisticsVO);
    }

    /**
     * 根据id查询订单详情
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<OrderVO> findOrderById(Long id) {
        Orders order = lambdaQuery()
                .eq(id != null, Orders::getId, id)
                .one();
        OrderVO orderVO = BeanUtil.toBean(order, OrderVO.class);
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery()
                .eq(id != null, OrderDetail::getOrderId, id)
                .list();
        if (orderDetailList.size() == 0) {
            return Result.success(orderVO);
        }
        orderVO.setOrderDetailList(orderDetailList);
        return Result.success(orderVO);
    }

    /**
     * 3.订单搜索
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<OrderPageVO> findOrderPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1.定义方法,分页查询订单信息
        Page<Orders> ordersPage = getOrdersPage(ordersPageQueryDTO);
        List<Orders> pageRecords = ordersPage.getRecords();
        List<OrderPageBeanVO> records = new ArrayList<>(pageRecords.size());
        for (Orders record : pageRecords) {
            records.add(BeanUtil.toBean(record, OrderPageBeanVO.class));
        }
        System.out.println("查询信息::" + records);
        return Result.success(new OrderPageVO(records, ordersPage.getTotal()));
    }

    /**
     * 分页查询方法
     *
     * @author: XieMingHui
     * @param: [ordersPageQueryDTO]
     * @return: MybatisPlus分页查询结果
     **/
    private Page<Orders> getOrdersPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        Integer status = ordersPageQueryDTO.getStatus(); //状态
        String number = ordersPageQueryDTO.getNumber(); // 订单id
        String phone = ordersPageQueryDTO.getPhone();   // 手机
        LocalDateTime beginTime = ordersPageQueryDTO.getBeginTime(); //开始时间
        LocalDateTime endTime = ordersPageQueryDTO.getEndTime(); // 截止时间
        Integer page = ordersPageQueryDTO.getPage(); //当前页
        Integer pageSize = ordersPageQueryDTO.getPageSize(); //长度
        if (page == null || pageSize == null) {
            page = 1;
            pageSize = 10;
        }
        // 拼接条件分页查询
        Page<Orders> ordersPage = lambdaQuery()
                .eq(status != null, Orders::getStatus, status)
                .like(StrUtil.isNotBlank(number), Orders::getNumber, number)
                .like(StrUtil.isNotBlank(phone), Orders::getPhone, phone)
                .ge(beginTime != null, Orders::getOrderTime, beginTime)
                .le(endTime != null, Orders::getOrderTime, endTime)
                .page(new Page<>(page, pageSize));
        return ordersPage;
    }

    /**
     * 4.取消订单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: [OrdersCancelDTO]
     * @return: 操作成功
     **/
    @Override
    @Transactional
    public Result<String> cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        String cancelReason = ordersCancelDTO.getCancelReason();
        Long id = ordersCancelDTO.getId();
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(id != null, Orders::getId, id)
                .eq(Orders::getStatus,Orders.CONFIRMED)
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelTime,LocalDateTime.now())
                .set(StrUtil.isNotBlank(cancelReason), Orders::getCancelReason, cancelReason);
        update(updateWrapper);

        return Result.success("操作成功");
    }

    /**
     * 5.拒单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: [OrdersRejectionDTO]
     * @return: 操作成功
     **/
    @Override
    @Transactional
    public Result<String> rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        String reason = ordersRejectionDTO.getRejectionReason();
        Long id = ordersRejectionDTO.getId();
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(id != null, Orders::getId, id)
                .eq(Orders::getStatus,Orders.TO_BE_CONFIRMED)
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelTime,LocalDateTime.now())
                .set(StrUtil.isNotBlank(reason), Orders::getRejectionReason, reason);

        update(updateWrapper);
        return Result.success("操作成功");

    }

    /**
     * 6. 确认接单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: [OrdersConfirmDTO]
     * @return: 操作成功
     **/
    @Override
    @Transactional
    public Result<String> confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Long confirmId = ordersConfirmDTO.getId();
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(confirmId != null, Orders::getId, confirmId)
                .eq(Orders::getStatus,Orders.TO_BE_CONFIRMED)
                .set(Orders::getStatus, Orders.CONFIRMED);
        update(updateWrapper);
        return Result.success("操作成功");
    }

    /**
     * 7.派送订单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: [订单id]
     * @return: 操作成功
     **/
    @Override
    @Transactional
    public Result<String> deliveryOrder(Long id) {
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(id != null, Orders::getId, id)
                .eq(Orders::getStatus,Orders.CONFIRMED)
                .set(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS);
        update(updateWrapper);
        return Result.success("操作成功");
    }

    /**
     * 8.完成订单
     *
     * @author: XieMingHui
     * @date: 23/11/21 8:32:05
     * @param: [订单id]
     * @return: 操作成功
     **/
    @Override
    @Transactional
    public Result<String> completeOrder(Long id) {
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(id != null, Orders::getId, id)
                .eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS)
                .set(Orders::getStatus, Orders.COMPLETED);
        update(updateWrapper);
        return Result.success("操作成功");

    }
    /**
     * 未知参数的接口尝试
     * @author: XieMingHui
     * @param: [undefinedOrderDTO]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<String> undefinedOrder(UndefinedOrderDTO undefinedOrderDTO) {
        Long id = undefinedOrderDTO.getId();
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(id != null, Orders::getId, id)
                .set(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS);
        update(updateWrapper);
        return Result.success("操作成功");
    }
    /**
     * 用户支付
     * @author: XieMingHui
     * @param: [ordersPaymentDTO]
     * @return: com.sky.result.Result<com.sky.vo.OrderPaymentVO>
     **/
    @Override
    public Result<OrderPaymentVO> payment(OrdersPaymentDTO ordersPaymentDTO) {
        String number = ordersPaymentDTO.getOrderNumber();
        Orders orders = lambdaQuery().eq(Orders::getNumber, number).one();
        Long ordersId = orders.getId();
        BigDecimal money =  orderDetailServiceMappe.sumMoney(ordersId);
        //跳过支付,直接成功,测试后续功能
        //支付成功后:修改订单号中对应订单的支付状态:true,订单状态:待接单,支付方式:为1微信,2是支付宝
        lambdaUpdate().eq(Orders::getNumber,number)
                .set(Orders::getPayMethod,Orders.WEI_XIN)
                .set(Orders::getPayStatus,true)
                .set(Orders::getStatus,Orders.TO_BE_CONFIRMED)
                .set(Orders::getAmount,money)
                .update();
        log.info("订单修改成功,向管理端发送消息提醒新订单");
        // 提醒管理端
        Map<String,Object> messageHash = new HashMap<>();
        messageHash.put("type",1);
        messageHash.put("orderId",ordersId);
        messageHash.put("content","订单号:"+number);
        String messageJsonStr = JSONUtil.toJsonStr(messageHash);
        webSocketServer.sendToAllClient(messageJsonStr);
        log.info("用户发起微信支付");
        // 复制黑马老师源码
        /*String orderNumber = ordersPaymentDTO.getOrderNumber(); // 获取订单号
        //根据订单号查询订单
        Orders order = lambdaQuery().eq(Orders::getNumber, orderNumber).one();
        BigDecimal amount = order.getAmount(); //订单金额
        Long userId = UserThreadUtil.getThread().getId();
        User user = userService.getById(userId);
        //调用微信支付接口，生成预支付交易单,获取响应体解析出JSON对象
        JSONObject jsonObject = null;
        try {
            jsonObject = weChatPayUtil.pay(
                    orderNumber, //参数1:商户订单号
                    amount, //参数2:支付金额，单位 元
                    "苍穹外卖订单", //参数3:商品描述
                    user.getOpenid() //微信用户的openid
            );
        } catch (Exception e) {
            throw new BaseException("支付异常,请重试");
        }*/
        // 创建一个空的对象,跳过前面的发起预支付订单步骤,假装订单已经支付
        JSONObject jsonObject = new JSONObject();
        // 判断是否支付
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        // 如果未支付,将响应数据封装到对象返回前端
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        // 将相关信息返回前端,前端会调用微信相关方法检验信息真伪,发起支付
        return Result.success(new OrderPaymentVO());

    }
    /**
     * 支付成功修改订单状态
     * @author: XieMingHui
     * @param: [ordersPaymentDTO]
     * @return: com.sky.result.Result<com.sky.vo.OrderPaymentVO>
     **/
    @Override
    public void updateOrderStartus(String outTradeNo) {
        // 前端支付后,微信会发起请求告知我们支付成功,也可以手动查询支付状态
        // 支付成功后:修改订单号中对应订单的支付状态:true,订单状态:待接单,支付方式:为1微信,2是支付宝
        if (StrUtil.isBlank(outTradeNo)){
            log.info("订单号为空");
            return ;
        }
        lambdaUpdate().eq(Orders::getNumber,outTradeNo)
                .set(Orders::getPayMethod,Orders.WEI_XIN)
                .set(Orders::getPayStatus,true)
                .set(Orders::getStatus,Orders.TO_BE_CONFIRMED)
                .update();
        log.info("订单修改成功");
    }

    /**
     * 用户查询订单详情
     * @author: XieMingHui
     * @param: [订单id]
     * @return: com.sky.result.Result<com.sky.vo.OrderVO>
     **/
    @Override
    public Result<OrderVO> orderDetails(Long id) {
        log.info("要查询的订单id:{}",id);
        Orders order = getById(id);
        OrderVO orderVO = BeanUtil.toBean(order, OrderVO.class);
        log.info("订单的信息:{}",orderVO);
        // 查询详情
        List<OrderDetail> OrderList = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, id).list();
        orderVO.setOrderDetailList(OrderList);
        log.info("封装好的订单的信息:{}",orderVO);
        return Result.success(orderVO);
    }
    /**
     * 用户取消订单
     * @author: XieMingHui
     * @param: [订单id]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<String> userCancel(Long id) {
        Orders order = getById(id);
        int status = order.getStatus();
        if(status>=3){
            log.info("商家已经接单,请与商家联系");
            return Result.error("取消失败,商家已接单");
        }
        boolean update = lambdaUpdate().set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelReason,"不吃了")
                .set(Orders::getCancelTime,LocalDateTime.now())
                .eq(Orders::getId, id).update();
        if (!update){
            return Result.error("取消失败");
        }
        return Result.success("取消成功");
    }
    /**
     * 用户历史订单查询
     * @author: XieMingHui
     * @param: [orderHistoryDTO]
     * @return: com.sky.result.Result<com.sky.vo.UserOrdersVO>
     **/
    @Override
    public Result<UserOrdersVO> historyOrders(OrderHistoryDTO orderHistoryDTO) {
        log.info("前端请求的参数{}",orderHistoryDTO);
        // 分页查询订单的方法
        Page<Orders> ordersPage = getOrdersPage(orderHistoryDTO);
        //获取当前页订单数据
        List<Orders> ordersList = ordersPage.getRecords();
        if (CollUtil.isEmpty(ordersList)){
            log.info("没有订单");
            return Result.success(new UserOrdersVO(0L, Collections.emptyList()));
        }
        // 获取当前页所有订单id
        List<Long> orderIdList = new ArrayList<>(ordersList.size());
        // 封装返回前端VO对象
        List<OrderVO> ordersVOList = new ArrayList<>(ordersList.size());
        ordersList.forEach(orders -> {
            orderIdList.add(orders.getId());
            ordersVOList.add(BeanUtil.toBean(orders,OrderVO.class));
        });
        // 转成MAP集合,订单id为key,订单对象为value
        //Map<Long, Orders> ordersMap = ordersList.stream().collect(Collectors.toMap(Orders::getId, v -> v));
        Map<Long, OrderVO> orderVOMap = CollStreamUtil.toMap(ordersVOList, OrderVO::getId, orderVO -> orderVO);
        // 2根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery()
                .in(OrderDetail::getOrderId, orderIdList).list();
        if (CollUtil.isEmpty(orderDetailList)){
            log.info("没有订单详情");
            return Result.success(new UserOrdersVO(ordersPage.getTotal(), ordersVOList));
        }
        // 3封装订单详情到对应的父级订单中
        encapsulationDetails(orderVOMap, orderDetailList);
        // 4返回前端
        log.info("返回前端的数据:{}",ordersVOList);
        return Result.success(new UserOrdersVO(ordersPage.getTotal(), ordersVOList));
    }
    // 用户端分页查询订单的方法
    private Page<Orders> getOrdersPage(OrderHistoryDTO orderHistoryDTO) {
        Long userId = UserThreadUtil.getThread().getId();
        // 1分页查询指定状态的所有订单
        Integer page = orderHistoryDTO.getPage();
        Integer pageSize = orderHistoryDTO.getPageSize();
        Integer status = orderHistoryDTO.getStatus();
        if (page==null||pageSize==null){
            page=1;pageSize=5;
        }
        //构建条件查询订单数据
        return lambdaQuery()
                .eq(Orders::getUserId,userId)
                .eq(status != null, Orders::getStatus, status)
                .page(new Page<>(page, pageSize));
    }

    // 用户端封装订单详情到对应的父级订单中
    private void encapsulationDetails(Map<Long, OrderVO> orderVOMap, List<OrderDetail> orderDetailList) {
        orderDetailList.forEach(orderDetail -> {
            // 获取订单对象
            OrderVO orderVO = orderVOMap.get(orderDetail.getOrderId());
            if (BeanUtil.isNotEmpty(orderVO)){
               if( CollUtil.isEmpty(orderVO.getOrderDetailList())){
                   // 如果订单对象中订单详情集合为空则创建一个新集合
                   orderVO.setOrderDetailList(new ArrayList<>());
               }
               // 添加对应的订单详情到集合中
                orderVO.getOrderDetailList().add(orderDetail);
            }
        });
    }

    /**
     * 用户再来一单
     *
     * @author: XieMingHui
     * @param: [id]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    @Transactional(rollbackFor =Exception.class)
    public Result<String> repetition(Long id) {
        Long userid = UserThreadUtil.getThread().getId();
        // 再来一单的逻辑是查询指定订单id的菜品信息,返回到购物车中,提供给用户下单使用
        log.info("再来一单的订单id:{}",id);
        // 查询指定订单id的详情信息
        List<OrderDetail> oldOrderList = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, id).list();
        // 购物车集合
        List<ShoppingCart> shoppingCartList = new ArrayList<>(oldOrderList.size());
        oldOrderList.forEach(orderDetail ->{
            ShoppingCart shoppingCart = BeanUtil.toBean(orderDetail, ShoppingCart.class);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(userid);
            // 封装到购物车集合
            shoppingCartList.add(shoppingCart);
        });
        // 添加到购物车
        iShoppingCarService.saveBatch(shoppingCartList);
        log.info("已添加到购物车:{}",shoppingCartList);
        return Result.success("已添加到购物车");
    }
    /**
     * 用户催单
     * @author: XieMingHui
     * @param: [id]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<String> reminder(Long id) {
        log.info("顾客来催单了,订单id:{}",id);
        Orders orders = getById(id);
        // 提醒管理端
        Map<String,Object> messageHash = new HashMap<>();
        messageHash.put("type",2);
        messageHash.put("orderId",id);
        messageHash.put("content","订单号:"+orders.getNumber());
        String messageJsonStr = JSONUtil.toJsonStr(messageHash);
        webSocketServer.sendToAllClient(messageJsonStr);
        log.info("催单成功,厨师抓紧烹饪中");
        return Result.success("催单成功,厨师抓紧烹饪中");
    }
    /**
     * 用户新增订单
     * @author: XieMingHui
     * @param: [orders]
     * @return: com.sky.result.Result<com.sky.vo.OrderSubmitVO>
     **/
    @Override
    @Transactional
    public Result<OrderSubmitVO> addOrder(Orders orders) {
        // 用地址id去获取手机号和地址等信息
        AddressBook address = iAddressBookService.findOneAddress(orders.getAddressBookId()).getData();
        if(BeanUtil.isEmpty(address)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 1.封装订单
        // 生成订单号:例如当天第一单 2023112300001
        // 获取下单时间
        LocalDateTime now = LocalDateTime.now();
        log.info("下单时间:{}",now);
        // 获取订单号
        String number = getOrderNumber(now);
        log.info("订单号:{}",number);
        // 获取下单用户id
        Long userId = UserThreadUtil.getThread().getId();
        // 获取用户信息
        User user = userService.getById(userId);
        // 依次封装各属性到订单对象
        orders.setOrderTime(now);
        orders.setNumber(number);
        orders.setUserId(userId);
        orders.setAmount(new BigDecimal("0.00")); // 设置初始实收金额为0
        orders.setPhone(address.getPhone());
        // 获取各级名称拼接地址
        orders.setAddress(address.getProvinceName()
                +address.getCityName()
                +address.getDistrictName()
                +address.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());
        // 添加订单到数据表.注入本类对象调用,让事务生效,缩小事务粒度
        Long orderId = GenerateOrders(orders);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orderId)
                .orderNumber(number)
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        // 清空购物车
        iShoppingCarService.cleanCar();
        return Result.success(orderSubmitVO);
    }
    // 生成订单
    @Transactional(rollbackFor = Exception.class)
    public Long GenerateOrders(Orders orders) {
        log.info("要保存的订单信息:{}",orders);
        boolean save = save(orders);
        if (!save){
            throw new BaseException("保存订单失败");
        }
        Long orderId = orders.getId(); // 订单号
        // 2.查询购物车中的商品,封装订单详情
        List<ShoppingCart> shoppingCartList = iShoppingCarService.findCar().getData();
        if (CollUtil.isEmpty(shoppingCartList)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        List<OrderDetail> orderDetailList = new ArrayList<>(shoppingCartList.size());
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail detail = BeanUtil.toBean(shoppingCart, OrderDetail.class);
            detail.setOrderId(orderId);
            orderDetailList.add(detail);
        }
        // 添加订单详情到订单详情数据表
        log.info("要保存的订单详情信息:{}",orderDetailList);
        boolean saveDetailResult = orderDetailService.saveBatch(orderDetailList);
        if (!saveDetailResult){
            throw new BaseException("保存订单详情失败");
        }
        return orderId;
    }

    // 获取订单号
    private String getOrderNumber(LocalDateTime now) {
        // 年月日转换字符串
        String timeStr = LocalDateTimeUtil.format(now, DatePattern.PURE_DATE_PATTERN);
        // 查询当天订单数
        Integer count = lambdaQuery().ge(Orders::getOrderTime, LocalDateTimeUtil.beginOfDay(now))
                .count();
        // 生成当天订单号
        String orderStr = "00000"+(count + 1);
        //
        return timeStr + orderStr.substring(orderStr.length() - 5);
    }
}
